package cn.fff.system.handler;

import cn.fff.common.result.Result;
import cn.fff.system.exception.FffCustomException;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<Void> exceptionHandler(Exception e) {
        e.printStackTrace();
        return Result.fail().message(e.getMessage());
    }

    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result<Void> arithmeticExceptionHandler(ArithmeticException e) {
        return Result.fail().message("特定异常 ArithmeticException 处理");
    }

    @ExceptionHandler(FffCustomException.class)
    @ResponseBody
    public Result<Void> fffCustomExceptionHandler(FffCustomException e) {
        return Result.fail().code(e.getCode()).message(e.getMsg());
    }

    @ExceptionHandler(ExpiredJwtException.class)
    @ResponseBody
    public Result<Void> expiredJwtExceptionHandler(ExpiredJwtException e) {
        return Result.fail().code(611).message("jwt token 过期");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<Void> methodArgumentNotValidException(MethodArgumentNotValidException ex) {

        String msg = ex.getFieldErrors().stream().map(e -> e.getDefaultMessage())
                .collect(Collectors.joining(", "));
        return Result.fail().code(612).message(msg);
    }
}
